package in.abip.chisame;

import in.abip.chisame.model.Remote;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Remote list activity
 * 
 * @author Julot
 * @since Friday, April 29, 2011
 */
public class RemoteListActivity extends ChisameActivity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_activity);
        populate();
        bind();
    }
	
    /** Populate room list by item from database. */
    @Override
    protected void populate() {
        ListView list = (ListView) findViewById(R.id.list);
        ListAdapter adapter = new ListAdapter(
    		this,
			R.layout.list_item,
			loadModels()
		);
		list.setAdapter(adapter);
	}
	
    /** Load models */
	private List<Object> loadModels() {
		Bundle bundle = getIntent().getExtras();
		List<Object> models = null;
		if (bundle != null) {
			models = Remote.model().findAll(
				"roomId = " + bundle.getInt("roomId")
			);
		}
		else models = Remote.model().findAll();
		return models;
	}
	
	/** Bind room list view to listener. */
	private void bind() {
		OnItemClickListener listener = new OnItemClickListener() {
			public void onItemClick(
				AdapterView<?> parent,
				View itemClicked,
				int position,
				long id
			) {
				ListAdapter adapter;
				adapter = (ListAdapter) parent.getAdapter();
				Remote model = (Remote) adapter.getItem(position);
				Bundle bundle = new Bundle();
				bundle.putLong("remoteId", model._id);
				Intent intent = new Intent(
					RemoteListActivity.this,
					RemoteActivity.class
				);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		};
		ListView list = (ListView) findViewById(R.id.list);
		list.setOnItemClickListener(listener);
	}
}
